package learning.maxent.training;

import learning.data.document.InstanceDocument;
import learning.maxent.inference.IParseScorer;
import learning.maxent.inference.Inference;
import learning.maxent.inference.Parse;

public class Maxent {

	public static DecodingResult decode(InstanceDocument doc,
			IParseScorer parseScorer, MaxentParameters parameters) {
		
		parseScorer.setDocument(doc);
		parseScorer.setParameters(parameters);
		
		Inference inf = new Inference(parameters.model);		
		Parse p = inf.parse(parseScorer);
		
		return new DecodingResult(p.label, p.score);
	}
	
	public static DecodingResult decode(InstanceDocument doc,
			MaxentParameters parameters) {
		IParseScorer parseScorer = new BasicParseScorer();
		return decode(doc, parseScorer, parameters);
	}
	
	public static void update(InstanceDocument doc, 
			DecodingResult predictedParse, DecodingResult trueParse,  
			MaxentParameters iterParameters, float delta) {
		int predictedLabel = predictedParse.label;
		int trueLabel = trueParse.label;
		
		if (predictedLabel != trueLabel) {
			iterParameters.parameters[predictedLabel].sum(doc.features, -delta);
			iterParameters.parameters[trueLabel].sum(doc.features, delta);
		}		
	}
	
	public static class DecodingResult {
		public int label;
		public float score;
		
		public DecodingResult(int label, float score) {
			this.label = label;
			this.score = score;
		}
	}
}